package com.ybear.ybcomponent.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.DrawableRes;
import androidx.core.content.ContextCompat;

import com.ybear.ybcomponent.R;
import com.ybear.ybcomponent.Utils;

public class EditTextClear extends androidx.appcompat.widget.AppCompatEditText implements View.OnFocusChangeListener, TextWatcher {
    private Drawable mClearDrawable;
    private boolean hasFocus;
    private boolean isClearIconVisibleAlways;
    private int mClearIconWidth;
    private int mClearIconHeight;
    private int mRtlLayoutState;

    public EditTextClear(Context context) { this( context, null ); }

    public EditTextClear(Context context, AttributeSet attrs) {
        this( context, attrs, android.R.attr.editTextStyle );
    }

    public EditTextClear(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mClearDrawable = getCompoundDrawablesRelative()[ 2 ];
        //默认Icon宽度和高度
        mClearIconWidth = mClearIconHeight = Utils.dp2Px( getContext(), 16 );
        //默认Icon资源图标
        setClearIconResources( R.drawable.ic_def_edit_text_clear, mClearIconWidth, mClearIconHeight );
        //设置焦点改变监听
        setOnFocusChangeListener( this );
        //设置内容监听
        addTextChangedListener( this );
    }

    /**
     清空图标总是可见
     @param isAlways    是否可见
     */
    public void setClearIconVisibleAlways(boolean isAlways) {
        isClearIconVisibleAlways = isAlways;
        if( isAlways ) setClearIconVisible( true );
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    public void setClearIconResources(@DrawableRes int resId, int iconWidth, int iconHeight) {
        if( getResources() == null ) return;
        //R.drawable.ic_edittext_clear
        setClearIconDrawable( ContextCompat.getDrawable( getContext(), resId ) , iconWidth, iconHeight );
    }

    public void setClearIconDrawable(Drawable drawable, int iconWidth, int iconHeight) {
        mClearDrawable = drawable;
        mClearIconWidth = iconWidth;
        mClearIconHeight = iconHeight;
        setClearIconVisible( isClearIconVisibleAlways );
    }

    public void setRtlLayout(boolean isRtlLayout) {
        mRtlLayoutState = isRtlLayout ? 1 : 2;
    }

    public boolean isRtlLayout() {
        if( mRtlLayoutState == 0 ) {
            return TextUtils.getLayoutDirectionFromLocale( getTextLocale() ) == View.LAYOUT_DIRECTION_RTL;
        }
        return mRtlLayoutState == 1;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if( event.getAction() != MotionEvent.ACTION_UP ) return super.onTouchEvent( event );
        if( mClearDrawable == null ) return super.onTouchEvent( event );
        Rect rect = mClearDrawable.getBounds();
        int w = getWidth();
        int x = (int) event.getX();
        int y = (int) event.getY();
        int distance = ( getHeight() - rect.height() ) / 2;
        int tpe = getTotalPaddingEnd();
        int pe = getPaddingEnd();
        //rtl适配
        if( isRtlLayout() ) x = w - x;
        boolean isInnerWidth = x >= w - tpe && x <= w + pe;
        boolean isInnerHeight = y > distance && y < ( distance + rect.height() );
        if( isInnerWidth && isInnerHeight ) this.setText( "" );
        return super.onTouchEvent( event );
    }

    /**
     * 设置icon是否可见
     */
    private void setClearIconVisible(boolean visible) {
        Drawable draw = isClearIconVisibleAlways || visible ? mClearDrawable : null;
        if( draw == null ) return;
        Drawable[] drawables = getCompoundDrawablesRelative();
        draw.setBounds( 0, 0, mClearIconWidth, mClearIconHeight );
        setCompoundDrawablesRelative( drawables[ 0 ], drawables[ 1 ], draw, drawables[ 3 ] );

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        setClearIconVisible( hasFocus && s.length() > 0 );
    }

    @Override
    public void afterTextChanged(Editable s) { }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        this.hasFocus = hasFocus;
        setClearIconVisible( hasFocus && ( getText() != null && getText().length() > 0 ) );
    }
}
